<template>
  <!-- 大组件内部的子布局：左侧树 + 拖动条 + 右侧内容 -->
  <div class="sub-layout">
    <!-- 左侧文件树 -->
    <div
        class="sidebar"
        :style="{ width: leftWidth + 'px' }"
    >
      <div class="search-container">
        <el-input
            v-model="databaseName"
            placeholder="请输入数据库名称"
            style="width: calc(100% - 80px); margin-right: 8px;"
            @keyup.enter="fetchTables"
        />
        <el-button
            type="primary"
            size="small"
            @click="fetchTables"
            :loading="loading"
        >
          搜索
        </el-button>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-tip">
        <el-loading :visible="true" :text="''" :spinner="Spinner" size="small"></el-loading>
        <span>加载中...</span>
      </div>

      <!-- 错误状态 -->
      <div v-if="error" class="error-tip">
        <el-icon color="#F56C6C"><WarningFilled /></el-icon>
        <span>{{ error.message || '加载失败，请重试' }}</span>
      </div>

      <!-- 树结构 -->
      <el-tree
          v-if="!loading && !error"
          :data="treeData"
          node-key="id"
          default-expand-all
          @node-click="handleNodeClick"
          @node-contextmenu="handleRightClick"
          :virtual-scroll="true"
      >
        <template #default="{ node, data }">
          <el-icon class="tree-icon">
            <component :is="icons[data.icon as keyof typeof icons]" />
          </el-icon>
          <span>{{ node.label }}</span>
        </template>
      </el-tree>

      <!-- 右键菜单 -->
      <ContextMenu
          :visible="contextMenuVisible"
          :x="menuPosition.x"
          :y="menuPosition.y"
          :current-row="currentRowData"
          @close="contextMenuVisible = false"

      />
      <AddTableDialog
          v-model="showAddTableDialog"
      />

    </div>

    <!-- 拖动条（可视化、可交互） -->
    <div
        class="resizer"
        @mousedown="startResize"
    ></div>

    <div class="main">
      <div class="main-inner">
        <!-- 替换原有文本为组件 -->
        <database-main
            v-if="selectedTable"
            :table-data="selectedTable"
        />
        <div v-else class="empty-tip">请选择数据表</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElTree, ElIcon, ElInput, ElMessage, ElButton, ElLoading } from 'element-plus'
import { Folder, Document, WarningFilled, Loading } from '@element-plus/icons-vue'
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useTableService } from '@/api/Table/TableApi.js'
import DatabaseMain from '@/views/DatabaseMain.vue'
import ContextMenu from '@/components/ContextMenu.vue'
import AddTableDialog from "@/views/AddTableDialog.vue";


// 定义弹窗状态
const showAddTableDialog = ref(false)


// 定义表数据类型
type TableData = {
  tableId: number
  tableName: string
  databaseName: string
  description?: string
  createdAt: string
}

// 定义树节点数据类型
interface TreeNodeData {
  id: string
  label: string
  icon: 'Folder' | 'Document'
  children?: TreeNodeData[]
  tableId?: number
  databaseName?: string
}

// 初始化服务
const {
  loading,
  error,
  response,
  getDataBaseByDatabaseName
} = useTableService()

// 搜索参数
const databaseName = ref('')

// 声明右键选中的节点
const selectedNode = ref<TreeNodeData | null>(null)

// 菜单状态
const contextMenuVisible = ref(false)
const menuPosition = ref({ x: 0, y: 0 })
// 定义当前行数据
const currentRowData = ref<TableData | null>(null)

// 获取表数据
const fetchTables = async () => {
  if (!databaseName.value.trim()) {
    return ElMessage.warning('请输入数据库名称')
  }
  // 重置状态
  selectedTable.value = null
  try {
    const res = await getDataBaseByDatabaseName({
      databaseName: databaseName.value,
      //将res赋值给response
    })

    console.log('获取表列表成功:', tables.value)
    if (tables.value.length === 0) {
      ElMessage.info('未找到数据表')
    }
  } catch (err) {
    console.error("获取表列表失败:", err)
    ElMessage.error('获取表列表失败: ' + (err instanceof Error ? err.message : String(err)))
  }
}
// 计算属性：提取表数据
const tables = computed<TableData[]>(() => {

  if (!response.value?.data?.data) return []

  return response.value.data.data.map(item  => ({
    tableId: item.tableId || 0,
    tableName: item.tableName?.trim() || '未命名表',
    databaseName: item.databaseName?.trim() || databaseName.value,
    description: item.description?.trim(),
    createdAt: item.createdAt || new Date().toISOString()
  }))
})

// 树结构数据
const treeData = computed<TreeNodeData[]>(() => {
  const dbId = `db-${databaseName.value || 'unknown'}`

  return [{
    id: 'root-db',
    label: '数据库',
    icon: 'Folder',
    children: [{
      id: dbId,
      label: databaseName.value || '未命名数据库',
      icon: 'Folder',
      children: tables.value.map(table => ({
        id: `table-${table.tableId}`,
        label: `${table.tableName}.sql`,
        icon: 'Document',
        tableId: table.tableId,
        databaseName: table.databaseName
      }))
    }]
  }]
})

// 选中的表
const selectedTable = ref<TableData | null>(null)

// 左侧面板宽度
const leftWidth = ref(220)
let isResizing = false
let startX = 0

// 右键点击处理 - 修正参数顺序：先事件，再数据
const handleRightClick = (event: MouseEvent, data: TreeNodeData) => {
  // 检查event是否有效
  if (event && typeof event.preventDefault === 'function') {
    event.preventDefault()
    event.stopPropagation()
  }

  selectedNode.value = data

  // 边界检查
  const menuWidth = 150 // 预估菜单宽度
  const menuHeight = 100 // 预估菜单高度
  const windowWidth = window.innerWidth
  const windowHeight = window.innerHeight

  let x = event.clientX
  let y = event.clientY

  // 确保菜单不超出右边界
  if (x + menuWidth > windowWidth) {
    x = windowWidth - menuWidth
  }

  // 确保菜单不超出下边界
  if (y + menuHeight > windowHeight) {
    y = windowHeight - menuHeight
  }

  menuPosition.value = { x, y }
  contextMenuVisible.value = true
}

// 拖动逻辑
const startResize = (e: MouseEvent) => {
  isResizing = true
  startX = e.clientX
  document.addEventListener('mousemove', handleResize)
  document.addEventListener('mouseup', stopResize)
  document.body.style.cursor = 'col-resize'
  document.body.style.userSelect = 'none'
}

const handleResize = (e: MouseEvent) => {
  if (!isResizing) return
  const delta = e.clientX - startX
  // 限制左侧最小宽度和最大宽度
  leftWidth.value = Math.max(35, Math.min(500, leftWidth.value + delta))
  startX = e.clientX
}

const stopResize = () => {
  isResizing = false
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
  document.body.style.cursor = ''
  document.body.style.userSelect = ''
}

// 处理节点点击
const handleNodeClick = (data: TreeNodeData) => {
  if (data.tableId) {
    const table = tables.value.find(t => t.tableId === data.tableId)
    if (table) {
      selectedTable.value = table
    }
  }
}


// 图标映射
const icons = { Folder, Document }
// 加载图标
const Spinner = Loading

// 清理事件监听
onUnmounted(() => {
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
})

// 生命周期钩子：初始化加载
onMounted(() => {
  // 可设置默认数据库名或提示用户输入
  // databaseName.value = 'default_db'
  // fetchTables()
})
</script>

<style scoped>
/* 父容器：继承大组件高度 */
.sub-layout {
  display: flex;
  height: calc(100% - 20px);
  overflow: hidden;
}

/* 搜索容器 */
.search-container {
  display: flex;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

/* 左侧树区域 */
.sidebar {
  background: #fff;
  border-right: 1px solid #e8e8e8;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

/* 树内容容器：滚动优化 */
.sidebar :deep(.el-tree) {
  flex: 1;
  overflow: auto;
  padding: 16px;
}

/* 加载和错误提示 */
.loading-tip, .error-tip {
  padding: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
}

.loading-tip :deep(.el-loading-spinner) {
  margin-right: 8px;
}

.error-tip {
  color: #F56C6C;
}

.error-tip :deep(.el-icon) {
  margin-right: 8px;
}

/* 拖动条：可视化、可交互 */
.resizer {
  width: 5px;
  background: #d9d9d9;
  cursor: col-resize;
  transition: background 0.2s;
  flex-shrink: 0;
}

.resizer:hover {
  background: #bfbfbf;
}

/* 右侧内容区域 */
.main {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #f8f9fa;
}

.main-inner {
  max-width: 1200px;
  margin: 0 auto;
}

/* 树节点样式 */
.tree-icon {
  color: #606266;
  margin-right: 6px;
}

:deep(.el-tree-node__content) {
  height: 36px;
  transition: background 0.2s;
}

:deep(.el-tree-node__content:hover) {
  background: var(--el-color-primary-light-9);
}

.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
  font-size: 16px;
}
</style>
